package com.cet.qz.unit01.chapter1_2;

import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdRandom;

import java.awt.*;

/**
 * @program: algorithm
 * @description:
 * @author: 陈恩涛
 * @create: 2021-02-26 21:17
 **/
public class Qz1_2_1 {

    public static double getCloestDist(int N) {

        //在单位正方形中生成N个随机点
        Point2D[] point2DS = new Point2D[N];

        for (int i = 0; i < N; i++) {
            point2DS[i] = new Point2D(StdRandom.uniform(),StdRandom.uniform());
            point2DS[i].draw();
        }

        double closestDist = point2DS[0].distanceTo(point2DS[1]);
        int start = 0;
        int end = 1;
        for (int i = 0; i < N; i++) {
            for (int j = i+1; j < N; j++) {
                double tempDist = point2DS[j].distanceTo(point2DS[i]);
                if (tempDist < closestDist) {
                    closestDist = tempDist;
                    start = i;
                    end = j;
                }
            }
        }

        StdDraw.setPenColor(Color.red);
        StdDraw.line(point2DS[start].x(),point2DS[start].y(),point2DS[end].x(),point2DS[end].y());

        return closestDist;
    }

    public static void main(String[] args) {
        System.out.println("请输入生成的随机点数：");
        int N = StdIn.readInt();
        System.out.println("随机点组成的最近线段的长度为"+getCloestDist(N));
    }
}
